package br.unb.cic.lp.gol;

import java.util.ArrayList;
import java.util.Collection;

public class Cell {
    private Collection<CellListener> cellListeners = new ArrayList<CellListener>();
    private boolean alive = false;

    public boolean isAlive() {
        return alive;
    }

    public void kill() {
        this.alive = false;
        disparaCelulaMorreu();
    }

    public void revive() {
        this.alive = true;
        disparaCelulaRessucitou();
    }

    public synchronized void addCellListener(CellListener l) {
        if ((!cellListeners.contains(l)))
            cellListeners.add(l);

    }

    public synchronized void removeCellListener(CellListener l) {
        cellListeners.remove(l);

    }

    private void disparaCelulaMorreu() {
        Collection<CellListener> cl;
        synchronized (this) {
            cl = (Collection) (((ArrayList) cellListeners).clone());
        }
        CellEvent evento = new CellEvent(this);
        for (CellListener c : cl)
            c.celulaMorreu(evento);
    }

    private void disparaCelulaRessucitou() {
        Collection<CellListener> cl;
        synchronized (this) {
            cl = (Collection) (((ArrayList) cellListeners).clone());
        }
        CellEvent evento = new CellEvent(this);
        for (CellListener c : cl)
            c.celulaRessucitou(evento);

    }
}
